package com.zyx.ip2region.hiveudf;

import com.zyx.ip2region.utils.AuxUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Yaxi.Zhang
 * @since 2021/9/1 15:14
 * 创建udf函数
 * hive > use your_db;
 * hive > drop function func_name;
 * 创建永久函数（指定库中创建）
 * hive > create function func_name as 'xxx.xxx.Ip2region' using jar 'hdfs:///user/hive/jars/xxx.jar';
 * 创建临时函数（可以在任意地方创建）
 * 重启hiveserver2
 * hive > desc function func_name;
 * hive > select myip2region(""124.236.223.17");
 * hive > select myip2region(""124.236'.223``.17");
 */
@Description(
        name = "myip2region",
        value = "_FUNC_(str) - parse ip to region info",
        extended = "Example: \n" +
                " SELECT myip2region(column) FROM hive_table; "
)
public class Ip2region extends UDF {

    private static InputStream in;
    private static byte[] data;
    private static final Pattern INTEGER_REGEX = Pattern.compile("[0-9]*");

    static {
        // 加载数据
        ByteArrayOutputStream out = null;
        try {
            Configuration configuration = new Configuration();
            FileSystem fileSystem = FileSystem.get(URI.create("hdfs:///user/hive/jars/ip2region.db"), configuration);
            in = fileSystem.open(new Path("hdfs:///user/hive/jars/ip2region.db"));
            out = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            while (in.read(b) != -1) {
                out.write(b);
            }
            // 提高性能,将ip2region.db一次从hdfs中读取出来，缓存到data字节数组中以重用
            // 避免每来一条数据读取一次ip2region.db
            data = out.toByteArray();
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String evaluate(String ip) throws Exception {

        if (ip == null) {
            return null;
        }

        DbConfig config = new DbConfig();
        DbSearcher searcher = new DbSearcher(config, data);
        if (AuxUtil.isIpAddress(ip)) {
            DataBlock dataBlock = searcher.memorySearch(ip);
            // 获取地域信息
            String[] split = dataBlock.getRegion().split("\\|");
            return AuxUtil.convert(split[0]) + ","
                    + AuxUtil.convert(split[2]) + ","
                    + AuxUtil.convert(split[3]) + ","
                    + AuxUtil.convert(split[4]);
        } else {
            return null;
        }

    }

}
